import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../atoms/getuser';
import { tbfduser } from '../../../atoms/db';
import md5 from '../../../atoms/md5';

const logger = anylogger('pages/api/account/resetpsw.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	userid: string;
};

/**
 * 重置密码为 123456
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const body = req.body as Message;
		const user = await getuser(req);
		if (user.role !== 'admin') {
			res.status(200).json({
				ok: false,
				message: 'Not allowed'
			});
			return;
		}
		const userid = body.userid;
		const u = await tbfduser().first('*').where({
			userid,
		});
		if (!u) {
			res.status(200).json({
				ok: false,
				message: '未查找到用户'
			});
			return;
		}
		await tbfduser()
			.update({
				psw: md5('123456')
			})
			.where({
				userid: u.userid
			});

		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
